package com.jspgou.cms.action.store;

import static com.jspgou.cms.Constants.STORE_SYS;

import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Website;
import com.jspgou.core.web.SiteUtils;
import com.jspgou.core.web.WebErrors;
import com.jspgou.cms.entity.Logistics;
import com.jspgou.cms.entity.Shipping;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.entity.Store;
import com.jspgou.cms.manager.LogisticsMng;
import com.jspgou.cms.manager.ShippingMng;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.cms.web.ShopFrontHelper;

@Controller
public class ShippingFroAct {
	private static final Logger log = LoggerFactory.getLogger(ShippingFroAct.class);
	
	/**
	 * 店铺物流列表页
	 */
	private static final String TPL_SHIPPING_STORE_LIST="tpl.shippingStoreList";
	/**
	 * 店铺物流添加页
	 */
	private static final String TPL_SHIPPING_STORE_ADD="tpl.shippingStoreAdd";
	/**
	 * 店铺物流修改页
	 */
	private static final String TPL_SHIPPING_STORE_EDIT="tpl.shippingStoreEdit";

	@RequestMapping("/shippingFro/list.jspx")
	public String list(String cl,Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		model.addAttribute("store", store);
		model.addAttribute("cl", cl);
		ShopFrontHelper.frontPageData(request, model);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_SHIPPING_STORE_LIST), request);
	}

	@RequestMapping("/shippingFro/add.jspx")
	public String add(HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store =member.getStore();
		model.addAttribute("store", store);
		ShopFrontHelper.frontPageData(request, model);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_SHIPPING_STORE_ADD), request);
	}

	@RequestMapping("/shippingFro/edit.jspx")
	public String edit(Long id, HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		List<Logistics> list=logisticsMng.getAllList();
		model.addAttribute("list", list);
		model.addAttribute("shipping", manager.findById(id));
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_SHIPPING_STORE_EDIT), request);
	}

	@RequestMapping("/shippingFro/save.jspx")
	public String save(Shipping bean, HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
	    bean.setStore(member.getStore());
	    bean.setIsDefault(false);
		bean = manager.save(bean);
		log.info("save Shipping. id={}", bean.getId());
		return "redirect:list.jspx";
	}

	@RequestMapping("/shippingFro/update.jspx")
	public String update(Shipping bean,Long logisticsId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		if(bean.getIsDefault()){
			List<Shipping> list=manager.getList((long)1,null, null,true);
			for(int i=0;i<list.size();i++){
				list.get(i).setIsDefault(false);
				manager.update(bean);
			}
		}
		bean.setLogistics(logisticsMng.findById(logisticsId));
		bean = manager.update(bean);
		log.info("update Shipping. id={}.", bean.getId());
//		return list(null,pageNo, request, model);
		return "redirect:list.jspx";
	}

	@RequestMapping("/shippingFro/delete.jspx")
	public String delete(Long[] ids, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Shipping[] beans = manager.deleteByIds(ids);
		for (Shipping bean : beans) {
			log.info("delete Shipping. id={}", bean.getId());
		}
//		return list(pageNo, request, model);
		return "redirect:list.jspx";
	}

	@RequestMapping("/shippingFro/priority.jspx")
	public String priority(Long[] wids, Integer[] priority, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validatePriority(wids, priority, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		manager.updatePriority(wids, priority);
		model.addAttribute("message", "global.success");
//		return list(pageNo, request, model);
		return "redirect:shippingFro/list.jspx";
	}

	private WebErrors validateSave(Shipping bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		bean.setWebsite(SiteUtils.getWeb(request));
		return errors;
	}

	private WebErrors validateEdit(Long id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifNull(id, "id");
		vldExist(id, errors);
		return errors;
	}

	private WebErrors validateUpdate(Long id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifNull(id, "id");
		vldExist(id, errors);
		return errors;
	}

	private WebErrors validateDelete(Long[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Long id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private WebErrors validatePriority(Long[] wids, Integer[] priority,
			HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (errors.ifEmpty(wids, "wids")) {
			return errors;
		}
		if (errors.ifEmpty(priority, "priority")) {
			return errors;
		}
		if (wids.length != priority.length) {
			errors.addErrorString("wids length not equals priority length");
			return errors;
		}
		for (int i = 0, len = wids.length; i < len; i++) {
			vldExist(wids[i], errors);
			if (priority[i] == null) {
				priority[i] = 0;
			}
		}
		return errors;
	}

	private boolean vldExist(Long id, WebErrors errors) {
		Shipping entity = manager.findById(id);
		return errors.ifNotExist(entity, Shipping.class, id);
	}

	@Autowired
	private ShippingMng manager;
	@Autowired
	private LogisticsMng logisticsMng;
}